
#include <iostream>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/freeglut.h>

#include "image.h"
#include "tools/logging.h"


Image image;
static GLuint   texName;
static float    angle = 0.0f;

void init(void)
{
    image.load("images/logo.png");
    glClearColor(0, 0, 0, 0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glGenTextures(1, &texName);
    glBindTexture(GL_TEXTURE_2D, texName);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.data()); 

    glEnable(GL_TEXTURE_2D);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glBindTexture(GL_TEXTURE_2D, texName);

    // glOrtho(0, 1, 0, 1, -1, 1);
    glOrtho(-1, 1, -1, 1, -1, 1);
}

void idle(void)
{
    angle += 0.0001f;
    glutPostRedisplay();
}

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

#if 0
    glColor3f(1.0f, 1.0f, 1.0f);
    glRotatef(angle, 0, 0, 1);

    glBegin(GL_POLYGON);
    // --
    
    glTexCoord2f(0, 0);
    // glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3f(-0.5, -0.5, 0.0);

    glTexCoord2f(0, 1);
    // glColor3f(1.0f, 0.0f, 1.0f);
    glVertex3f(-0.5, 0.5, 0.0);

    glTexCoord2f(1, 1);
    // glColor3f(1.0f, 1.0f, 0.0f);
    glVertex3f(0.5, 0.5, 0.0);

    glTexCoord2f(1, 0);
    // glColor3f(0.0f, 1.0f, 1.0f);
    glVertex3f(0.5, -0.5, 0.0);

    // --
    glEnd();
#else
    // glOrthof(-1, 1, -1, 1, -1, 1);
    GLfloat vtx[] = {
        -0.5, -0.5, 0,
        -0.5, 0.5, 0,
        0.5, 0.5, 0,
        0.5, -0.5, 0
    };
    GLfloat tex[] = {
        0, 0,
        0, 1,
        1, 1,
        1, 0
    };
    glRotatef(angle, 0, 0, 1);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(3, GL_FLOAT, 0, vtx);
    glTexCoordPointer(2, GL_FLOAT, 0, tex);

    glDrawArrays(GL_POLYGON, 0, 4);

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
#endif
    glFlush();
}

int main(int argc, char ** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
    glutInitWindowSize(512, 512);
    // glutInitContextVersion(3, 2);
    // glutInitContextProfile(GLUT_CORE_PROFILE);
    glutCreateWindow(argv[0]);
    // if (glewInit()) {
    //     FATAL() << "Unable to initialize GLEW ...";
    //     return EXIT_FAILURE;
    // }
    init();
    glutDisplayFunc(display);
    glutIdleFunc(idle);
    glutMainLoop();
    return 0;
}

